﻿using _RobotInspection.DTO;
using _RobotInspection.Entities;
using _RobotInspection.Interfaces;
using _RobotInspection.Models;
using Microsoft.AspNetCore.Mvc;
using RobotInspection.Entities;
using SqlSugar;

namespace _RobotInspection.Services
{
    /// <summary>
    /// 点检项目服务层实现类
    /// </summary>
    public class InspectionItemService : IInspectionItemService
    {
        private readonly ISqlSugarClient _db;
        private readonly ILogger<InspectionItemService> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="db"></param>
        /// <param name="logger"></param>
        public InspectionItemService(ISqlSugarClient db, ILogger<InspectionItemService> logger)
        {
            _db = db;
            _logger = logger;
        }

        /// <summary>
        /// 异步按设备Id查询点检项目
        /// </summary>
        /// <param name="equipmentId"></param>
        /// <returns></returns>
        public async Task<ApiResponse<List<inspection_items>>> GetItemsByEquipmentIdAsync(long equipmentId)
        {
            try
            {
                // 检验设备是否存在
                var equipmentNumber = await _db.Queryable<equipment>().Where(e => e.id == equipmentId).CountAsync();
                if (equipmentNumber == 0) 
                { 
                    return ApiResponse<List<inspection_items>>.Error("查询点检项目失败：设备不存在", 400); 
                }

                // 查询点检项目
                var itemList = await _db.Queryable<inspection_items>().Where(i => i.equipment_id == equipmentId).ToListAsync();
                return ApiResponse<List<inspection_items>>.Success(itemList, null);
            }
            catch (Exception ex) 
            {
                return ApiResponse<List<inspection_items>>.Error($"设备删除失败：{ex.Message}", 500);
            }

        }

        /// <summary>
        /// 异步创建点检项目
        /// </summary>
        /// <param name="queryDto"></param>
        /// <returns></returns>
        public async Task<ApiResponse<inspection_items>> InsertItemAsync(InspectionItemInsertDto queryDto)
        {
            // 检验设备Id是否合法
            if (queryDto.EquipmentId <= 0)
            {
                return ApiResponse<inspection_items>.Error("添加点检项目失败：设备Id不合法", 400);
            }
            try
            {
                // 检验设备是否存在
                var equipmentNumber = await _db.Queryable<equipment>().Where(e => e.id == queryDto.EquipmentId).CountAsync();
                if (equipmentNumber == 0)
                {
                    return ApiResponse<inspection_items>.Error("添加点检项目失败：设备不存在", 400);
                }

                //创建点检项目数据
                var item = new inspection_items
                {
                    equipment_id = queryDto.EquipmentId,
                    item_name = queryDto.ItemName,
                    item_description = queryDto.ItemDescription ?? "",
                    item_project = queryDto.ItemProject ?? "",
                    standard_value = queryDto.StandardValue ?? "",
                    unit = queryDto.Unit ?? "",
                    sort_order = queryDto.SortOrder,
                    status = queryDto.Status ?? 1,
                    created_at = DateTime.Now,
                    updated_at = DateTime.Now
                };
                // 插入点检项目数据
                var itemResult = await _db.Insertable(item).ExecuteReturnEntityAsync();
                return ApiResponse<inspection_items>.Success(itemResult, "点检项目创建成功");
            }
            catch (Exception ex)
            {
                return ApiResponse<inspection_items>.Error($"添加点检项目失败：{ex.Message}", 500);
            }
        }

        /// <summary>
        /// 异步修改点检项目
        /// </summary>
        /// <param name="queryDto"></param>
        /// <returns></returns>
        public async Task<ApiResponse<inspection_items>> UpdateItemAsync(InspectionItemUpdateDto queryDto)
        {
            // 检验id是否合法
            if (queryDto.Id <= 0 && queryDto.EquipmentId <= 0)
            {
                return ApiResponse<inspection_items>.Error("点检项目修改失败：点检项目ID与设备ID无效", 400);
            }

            try
            {
                // 检验点检项目是否存在
                var inspectionItemList = await _db.Queryable<inspection_items>().Where(i => i.id == queryDto.Id).ToListAsync();
                if (inspectionItemList.Count != 1)
                {
                    return ApiResponse<inspection_items>.Error("点检项目修改失败：点检项目ID不存在或错误", 400);
                }

                // 检验是否需要判断设备id
                if (queryDto.EquipmentId.HasValue)
                {
                    // 检验设备是否存在
                    var equipmentList = await _db.Queryable<equipment>().Where(i => i.id == queryDto.EquipmentId).ToListAsync();
                    if (equipmentList.Count != 1)
                    {
                        return ApiResponse<inspection_items>.Error("点检项目修改失败：设备ID不存在或错误", 400);
                    }
                }
                
                //创建点检项目数据结构
                var inspectionItemUpdate = new inspection_items
                {
                    id = queryDto.Id,
                    equipment_id = queryDto.EquipmentId ?? inspectionItemList[0].equipment_id,
                    item_name = queryDto.ItemName ?? inspectionItemList[0].item_name,
                    item_description = queryDto.ItemDescription ?? inspectionItemList[0].item_description,
                    standard_value = queryDto.StandardValue ?? inspectionItemList[0].standard_value,
                    unit = queryDto.Unit ?? inspectionItemList[0].unit,
                    sort_order = queryDto.SortOrder ?? inspectionItemList[0].sort_order,
                    status = queryDto.Status ?? inspectionItemList[0].status,
                    created_at = inspectionItemList[0].created_at,
                    updated_at = DateTime.Now

                };
                var inspectionItemResult = await _db.Updateable(inspectionItemUpdate).ExecuteReturnEntityAsync();

                return ApiResponse<inspection_items>.Success(inspectionItemResult, "点检项目修改成功");

            }
            catch (Exception ex)
            {
                return ApiResponse<inspection_items>.Error($"点检项目修改失败：{ex.Message}", 500);
            }
        }

        /// <summary>
        /// 异步按id删除点检项目
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ApiResponse<inspection_items?>> DeleteItemAsync(long id)
        {
            // 检验id是否合法
            if (id <= 0)
            {
                return ApiResponse<inspection_items?>.Error("删除点检项目失败：点检项目Id不合法", 400);
            }
            try
            {
                // 检验点检项目是否存在
                var itemNumber = await _db.Queryable<inspection_items>().Where(i => i.id == id).CountAsync();
                if (itemNumber == 0)
                {
                    return ApiResponse<inspection_items?>.Error("删除点检项目失败：点检项目不存在", 400);
                }

                await _db.Deleteable<inspection_items>().Where(i => i.id == id).ExecuteCommandAsync();

                return ApiResponse<inspection_items?>.Success(null, "点检项目删除成功");

            }
            catch (Exception ex) 
            {
                return ApiResponse<inspection_items?>.Error($"删除点检项目失败：{ex.Message}", 500);
            }
        }

        /// <summary>
        /// 批量删除点检项目
        /// </summary>
        /// <param name="idList"></param>
        /// <returns></returns>
        public async Task<ApiResponse<List<string>>> DeleteItemListAsync(List<long> idList)
        {
            List<string> messageList = [];
            foreach (var id in idList)
            {
                // 检验id是否合法
                if (id <= 0)
                {
                    return ApiResponse<List<string>>.Error($"删除点检项目失败：点检项目{id}Id不合法", 400);
                }
                try
                {
                    // 检验点检项目是否存在
                    var itemNumber = await _db.Queryable<inspection_items>().Where(i => i.id == id).CountAsync();
                    if (itemNumber == 0)
                    {
                        return ApiResponse<List<string>>.Error($"删除点检项目失败：点检项目{id}不存在", 400);
                    }

                    await _db.Deleteable<inspection_items>().Where(i => i.id == id).ExecuteCommandAsync();

                    string message = $"点检项目{id}删除成功";
                    messageList.Add(message);
                }
                catch (Exception ex)
                {
                    return ApiResponse<List<string>>.Error($"删除点检项目失败：{ex.Message}", 500);
                }
            }
            return ApiResponse<List<string>>.Success(messageList, $"{idList.Count}个点检项目删除成功");
        }
    }
}
